using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

using Wicresoft.Messages.BusinessLogic;
using Wicresoft.Messages.Entity;
using Wicresoft.Messages.Implementation;
using Wicresoft.Messages.Interface;

namespace Wicresoft.Messages.Interface
{
    class IncomingProcessorFactory
    {
        public static IIncomingProcessor CreateIncomingProcessor(int incomingProcessorType)
        {
            if (_incomingProcessFactory.ProcessorCache[incomingProcessorType] == null)
            {
                Device device = BLMessage.GetSingleDevice(incomingProcessorType);
                try
                {
                    string assemblyFilename = device.AssemblyName;
                    string className = device.IncomingClassName;
                    Assembly currentAssembly = Assembly.GetAssembly(typeof(IncomingProcessorFactory));
                    string assemblyFullname = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), assemblyFilename);
                    Assembly assembly = Assembly.LoadFile(assemblyFullname);
                    Type type = assembly.GetType(className);
                    IIncomingProcessor processor = Activator.CreateInstance(type) as IIncomingProcessor;
                    _incomingProcessFactory.ProcessorCache[incomingProcessorType] = processor;
                }
                catch
                {
                    _incomingProcessFactory.ProcessorCache[incomingProcessorType] = Activator.CreateInstance(typeof(WebIncomingProcessor)) as IIncomingProcessor;
                }
            }
            return _incomingProcessFactory.ProcessorCache[incomingProcessorType] as IIncomingProcessor;
        }

        private static IncomingProcessorFactory _incomingProcessFactory = new IncomingProcessorFactory();
        private Hashtable ProcessorCache = new Hashtable();
    }
}
